package com.sgq.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sgq.entity.User;
import com.sgq.service.UserService;
import com.sgq.utils.Result;
import com.sgq.vo.UserQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sgq
 * @since 2024-09-13
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public Result getUserById(@PathVariable("id") Long id){
        return Result.ok(userService.getById(id));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user')")
    public Result list(){
        List<User> list = userService.list();
        return Result.ok(list);
    }

    @GetMapping("/page")
    @PreAuthorize("hasAuthority('sys:user')")
    public Result page(UserQueryVo userQueryVo){
        IPage<User> page = userService.findPage(userQueryVo);
        return Result.ok(page);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public Result save(@RequestBody User user){
        //TO DO: 密码加密
        return Result.ok(userService.save(user));
    }

    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public Result update(@RequestBody User user){
        return Result.ok(userService.updateById(user));
    }

    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@PathVariable("id") Long id){
        return Result.ok(userService.removeById(id));
    }

    @DeleteMapping("/deleteBatch")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result deleteBatch(@RequestBody Long [] ids){
        return Result.ok(userService.removeBatchByIds(Arrays.asList(ids)));
    }


}

